﻿using Commission.DAL;
using Commission.Models;
using Microsoft.AspNet.Identity;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Commission.Controllers
{
    public class ChartController : BaseController
    {
        private CustomerRepository db = new CustomerRepository(new SchoolContext());

        // GET: Chart
        public ActionResult Home()
        {
            return RedirectToAction("Index", "Home"); 
        }

        public ActionResult SubCustomerSearch(string term)
        {
            bool isAdmin = User.IsInRole("Admin");

            string[] userNames = null;

            if (isAdmin)
            {
                IEnumerable<Customer> customers = db.GetCustomers();
                userNames =
                    customers.Select(p => p.UserName)
                    .Concat(customers.Select(p => p.Name)).ToArray();
            }
            else
            {
                Customer customer = db.GetCustomerByUserName(User.Identity.GetUserName());

                if (customer != null)
                {
                    IList<Customer> customers = customer.AllSubCustomers();
                    customers.Insert(0, customer);

                    userNames =
                        customers.Select(p => p.UserName)
                        .Concat(customers.Select(p => p.Name)).ToArray();
                }
            }

            return this.Json(userNames
                .Where(t => t.ToUpper().Contains(term.ToUpper())), JsonRequestBehavior.AllowGet);
        }
    }
}